import React, { useState, useEffect } from 'react';
import { isAuthenticated, onAuthChange } from '../utils/auth';
import AdminLogin from './AdminLogin';

interface AdminProtectedProps {
  children: React.ReactNode;
}

const AdminProtected: React.FC<AdminProtectedProps> = ({ children }) => {
  const [isAuth, setIsAuth] = useState(false);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    // 初始检查认证状态
    const checkAuth = () => {
      setIsAuth(isAuthenticated());
      setIsChecking(false);
    };

    checkAuth();

    // 监听认证状态变化
    const cleanup = onAuthChange((authStatus) => {
      setIsAuth(authStatus);
    });

    return cleanup;
  }, []);

  const handleLogin = () => {
    setIsAuth(true);
  };

  // 正在检查认证状态时显示加载界面
  if (isChecking) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">检查认证状态...</div>
      </div>
    );
  }

  // 如果未认证，显示登录界面
  if (!isAuth) {
    return <AdminLogin onLogin={handleLogin} />;
  }

  // 如果已认证，显示受保护的内容
  return <>{children}</>;
};

export default AdminProtected;
